package cn.hamster3.hamsterworld.listener;

import cn.hamster3.hamsterworld.core.DataManager;
import cn.hamster3.hamsterworld.core.Message;
import cn.hamster3.hamsterworld.data.WorldData;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerTeleportEvent;

public class MainListener implements Listener {
    private DataManager dataManager;

    public MainListener(DataManager dataManager) {
        this.dataManager = dataManager;
    }

    @EventHandler(ignoreCancelled = true)
    public void worldPermissionCheck(PlayerTeleportEvent event) {
        Location location = event.getTo();
        World world = location.getWorld();
        if (dataManager.isWhiteList(world.getName())) {
            return;
        }
        Player player = event.getPlayer();
        WorldData worldData = dataManager.getWorldData(world);
        if (worldData == null) {
            return;
        }
        if (worldData.isAllowed(player)) {
            return;
        }
        player.sendMessage(Message.cantEnterWorld.toString().replace("%player%", world.getName()));
        event.setCancelled(true);
        OfflinePlayer owner = Bukkit.getOfflinePlayer(worldData.getOwner());
        if (owner == null || !owner.isOnline()) {
            return;
        }
        owner.getPlayer().sendMessage(Message.cantEnterOwnerNotify.toString().replace("%player%", player.getName()));
    }
}
